<template>
  <!-- eslint-disable -->
  <div class="home-page">
    <div class="banner">
      <div class="container">
        <h1 class="logo-font">conduit</h1>
        <p>A place to share your knowledge.</p>
      </div>
    </div>

    <div class="container page">
      <div class="row">
        <div class="col-md-9">
          <div class="feed-toggle">
            <ul class="nav nav-pills outline-active">
              <li v-if="user" class="nav-item">
                <nuxt-link
                  class="nav-link"
                  exact
                  :class="{
                    active: tab === 'your_feed'
                  }"
                  :to="{
                    name: 'Home',
                    query: {
                      tab: 'your_feed'
                    }
                  }"
                  >Your Feed</nuxt-link
                >
              </li>
              <li class="nav-item">
                <nuxt-link
                  class="nav-link"
                  exact
                  :class="{
                    active: tab === 'global_feed'
                  }"
                  :to="{
                    name: 'Home',
                    query: {
                      tab: 'global_feed'
                    }
                  }"
                  >Global Feed</nuxt-link
                >
              </li>
              <li v-if="tag" class="nav-item">
                <nuxt-link
                  class="nav-link"
                  exact
                  :class="{
                    active: tab === 'tag'
                  }"
                  :to="{
                    name: 'Home',
                    query: {
                      tab: 'tag',
                      tag
                    }
                  }"
                  >{{ tag }}</nuxt-link
                >
              </li>
            </ul>
          </div>

          <div class="article-preview" v-for="ele in articles" :key="ele.slug">
            <div class="article-meta">
              <nuxt-link
                :to="{
                  name: 'Profile',
                  params: {
                    username: ele.author.username
                  }
                }"
                ><img :src="ele.author.image"
              /></nuxt-link>
              <div class="info">
                <nuxt-link
                  :to="{
                    name: 'Profile',
                    params: {
                      username: ele.author.username
                    }
                  }"
                  class="author"
                  >{{ ele.author.username }}</nuxt-link
                >
                <span class="date">{{
                  ele.createdAt | date('MMM DD, YYYY')
                }}</span>
              </div>
              <button
                class="btn btn-outline-primary btn-sm pull-xs-right"
                :class="{ active: ele.favorited }"
                @click="onFavorite(ele)"
                :disabled="ele.favoriteDisabled === true"
              >
                <i class="ion-heart"></i> {{ ele.favoritesCount }}
              </button>
            </div>
            <nuxt-link
              :to="{
                name: 'Article',
                params: {
                  slug: ele.slug
                }
              }"
              class="preview-link"
            >
              <h1>{{ ele.title }}</h1>
              <p>{{ ele.description }}</p>
              <span>Read more...</span>
            </nuxt-link>
          </div>
        </div>

        <div class="col-md-3">
          <div class="sidebar">
            <p>Popular Tags</p>

            <div class="tag-list">
              <nuxt-link
                :to="{
                  name: 'Home',
                  query: {
                    tag: ele,
                    tab: 'tag'
                  }
                }"
                class="tag-pill tag-default"
                v-for="(ele, index) in tags"
                :key="index"
              >
                {{ ele }}
              </nuxt-link>
            </div>
          </div>
        </div>
        <el-pagination
          style="margin:10px auto;"
          layout="prev, pager, next"
          :total="articlesCount"
          :page-size="limit"
          :current-page="page"
          @current-change="changePage"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
/*eslint-disable */
import { mapState } from 'vuex'
import {
  getArticles,
  getTags,
  getYourFeedArticle,
  addFavorite,
  deleteFavorite
} from './api/index'
export default {
  watchQuery: ['page', 'tag', 'tab'], //监听url查询字符串的某个值的变化，变化则重新执行asyncData
  name: 'Home',
  created() {
    console.log(this.articles)
    console.log(this.articlesCount)
    console.log(this.tags)
  },
  data() {
    return {}
  },
  computed: {
    ...mapState(['user'])
  },
  async asyncData({
    isDev,
    route,
    store,
    env,
    params,
    query,
    req,
    res,
    redirect,
    error
  }) {
    const limit = 10
    const page = Number(query.page || 1)
    const tab = query.tab || 'global_feed'
    const tag = query.tag
    const loadArticles =
      tab === 'global_feed' || tab === 'tag' ? getArticles : getYourFeedArticle
    const all = await Promise.all([
      loadArticles({
        limit,
        offset: (page - 1) * limit,
        tag: query.tag
      }),
      getTags()
    ])
    console.log(all)
    return {
      articles: all[0].data.articles.map((ele) => {
        ele.favoriteDisabled = false
        return ele
      }),
      articlesCount: all[0].data.articlesCount,
      tags: all[1].data.tags,
      page,
      limit,
      tab,
      tag
    }
  },
  methods: {
    changePage(page) {
      console.log(page)
      this.$router.push({
        path: '/',
        query: {
          page,
          tag: this.$route.query.tag,
          tab: this.tab
        }
      })
    },
    async onFavorite(article) {
      console.log(article)
      try {
        article.favoriteDisabled = true
        if (article.favorited) {
          await deleteFavorite(article.slug)
          article.favorited = false
          if (article.favoritesCount > 0) {
            article.favoritesCount -= 1
          }
        } else {
          await addFavorite(article.slug)
          article.favorited = true
          article.favoritesCount += 1
        }
      } catch (error) {
        console.log(error)
      } finally {
        article.favoriteDisabled = false
      }
    }
  }
}
</script>

<style scoped></style>
<style>
.el-pager li.active {
  color: rgb(92, 184, 92) !important;
}
.el-pager li:hover {
  color: rgb(92, 184, 92) !important;
}
</style>
